<?php
namespace Apipad\Controller;
//商品采集
header("content-type:application/json;charset=utf-8");
class GoodsmtController extends CommonController{
     //采集供应链商品接口
     public function setapi_caiji(){
        $detail= I('post.');
        $goods_id=$detail['goods_id'];
        $where['id'] =1;
        $model= M("zymaimai_api"); 
        $uid=UID;
        $dfgg = $model->where($where)->find();
        if($goods_id){
            $goods_count=M("user_goods")->where(['zymm_goods_id'=>$goods_id,'uid'=>$uid,'isdel'=>0])->count();
            if($goods_count){
                $data_cc['code']=0;
                $data_cc['msg']='该商品已经采集过了啊';
                exit(json_encode($data_cc));
            }
            $datfr=[];
            $datfr['user_name']=$dfgg['user_name'];
            $datfr['app_key']=$dfgg['app_key'];
            $datfr['goods_id']=$goods_id;
            $jsonStr = json_encode($datfr); 
            $url = "https://www.zymaimai.cn/apis_gtest.php?method=hc_goods_info&interface_type=1";
            $url.="&user_name".$dfgg['user_name']."&app_key=".$dfgg['app_key']."&goods_id=".$goods_id;
            $header = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
            $resault = $this->http($url,$datfr,'GET',$header);
            $mt=json_decode($resault,true);
            if($mt['error']==200){
                $goods_data=$mt['data']['goods_info'];
                $goods_type=$mt['data']['goods_type'];
                $goods_attr=$mt['data']['goods_attr'];
                $cctt=count($goods_attr['attr_group']);
                $chimacc=$mt['data']['chimacc'];
                if($cctt>2){
                    $data_cc['code']=0;
                    $data_cc['msg']='该商品组合超过3组，无法采集。';
                    exit(json_encode($data_cc));
                }
                //入库操作
                $yanse_chima=$goods_attr['yanse_chima'];
                $yanse1=$mt['data']['goods_attr']['attr_group'];
                $yanse_list=$yanse1[0]['attr_list'];
                $guige_list=$yanse1[1]['attr_list'];
                $color='';
                $guige_name='';
                if($yanse_list){
                      foreach($yanse_list as $k=>$val){
                        $color.=$val['attr_value'].',';
                      }
                      $color=rtrim($color,',');
                }
                if($guige_list){
                    foreach($guige_list as $k1=>$vals){
                      $guige_name.=$vals['attr_value'].',';
                    }
                    $guige_name=rtrim($guige_name,',');
              }
                $goods_type_id=$this->checkcate($goods_type);//先插入分类
                $goods_data['goods_type_id']=$goods_type_id;//分类ID
                $add_goods_id=0;
                $add_goods_id =$this->addgoods($goods_data,$goods_type_id,$color,$guige_name);
                //插入规格
                if($yanse_chima){
                    $cdsat['add_goods_id']=$add_goods_id;
                    $cdsat['goods_name']=$goods_data['goods_name'];
                    $cdsat['goods_price']=$goods_data['market_sell_price'];
                    $cdsat['goods_price2']=$goods_data['wholesale_price'];
                }
                if($add_goods_id){
                    if($cdsat){
                        $this->add_goods_guige($yanse_chima,$cdsat);
                    }
                    $data_cc['code']=200;
                    $data_cc['msg']='采集成功';
                    $data_cc['data']['goods_id']=$add_goods_id;
                    $data_cc['data']['zymm_goods_id']=$goods_data['zymm_goods_id'];
                    exit(json_encode($data_cc));
                }
            }else{
                    $data_cc['code']=0;
                    $data_cc['msg']='信息查询失败';
                    exit(json_encode($data_cc));
            }
            
        }else{
            $data_cc['code']=0;
            $data_cc['msg']='参数错误';
            exit(json_encode($data_cc));
        }
        
    }

    //商品列表
    public function goodslist(){
        $data = I('post.');
        $uid=UID;
        $page = isset($data['page']) ? $data['page'] : 1;
        $page = empty($page) ? 1 : $page;
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $limit = empty($limit) ? 10 : $limit;
        $kewords = empty($data['keyword']) ? '' : $data['keyword'];
        $cate_id =  isset($data['cate_id']) ? $data['cate_id'] : '';
        $price_min='';
        $price_max='';
        $sort='';
        $where['id'] =1;
        $model= M("zymaimai_api"); 
        $dfgg = $model->where($where)->find();
        $datfr=[];
        $datfr['user_name']=$dfgg['user_name'];
        $datfr['app_key']=$dfgg['app_key'];
        $datfr['page']=$page;
        $datfr['limit']=$limit;
        $datfr['kewords']=$kewords;
        $datfr['cate_id']=$cate_id;
        $datfr['price_min']=$price_min;
        $datfr['price_max']=$price_max;
        $datfr['sort']=$sort;
        $url = "https://www.zymaimai.cn/apis_test.php?method=goods_list&interface_type=1";
        $url.="&user_name".$dfgg['user_name']."&app_key=".$dfgg['app_key']."&page=".$page."&limit=".$limit."&kewords=".$kewords."&cate_id=".$cate_id."&price_min=".$price_min."&price_max=".$price_max."&sort=".$sort;
        $header = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        $resault = $this->http($url,$datfr,'GET',$header);
        $mt=json_decode($resault,true);
        if($mt['error']==200){
            $goods_list=$mt['data']['goods_list'];
            //查询商品是否已采集
            if($goods_list){
                foreach($goods_list as $k=>$val){
                    $fsg=M("user_goods")->where(['zymm_goods_id'=>$val['goods_id'],'uid'=>$uid])->count();
                    $goods_list[$k]['iscjcc']=$fsg?:0;
                }
            }
            $total=$mt['data']['total'];
            $data_cc['code']=200;
            $data_cc['msg']='查询成功';
            $data_cc['data']['count']=$total;
            $data_cc['data']['list']=$goods_list;
            exit(json_encode($data_cc));
        }else{
            $data_cc['code']=0;
            $data_cc['msg']='接口错误';
            exit(json_encode($data_cc));
        }
        
   }
     /*商品分类*/
    public function goodsTypeList(){
        $where['id'] =1;
        $model= M("zymaimai_api"); 
        $dfgg = $model->where($where)->find();
        $datfr=[];
        $datfr['user_name']=$dfgg['user_name'];
        $datfr['app_key']=$dfgg['app_key'];
        $url = "https://www.zymaimai.cn/apis_test.php?method=getcate_cc&interface_type=1";
        $url.="&user_name".$dfgg['user_name']."&app_key=".$dfgg['app_key'];
        $header = array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
        $resault = $this->http($url,$datfr,'GET',$header);
        $mt=json_decode($resault,true);
        $list=$mt['data'];
        $data_cc['code']=200;
        $data_cc['msg']='查询成功';
        $data_cc['data']['list']=$list;
        exit(json_encode($data_cc));
    }

        /**
     * 发送HTTP请求方法
     * @param  string $url    请求URL
     * @param  array  $params 请求参数
     * @param  string $method 请求方法GET/POST
     * @return array  $data   响应数据
     */
    function http($url, $params, $method = 'GET', $header = array(), $multi = false){
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER     => $header
        );
        /* 根据请求类型设置特定参数 */
        switch(strtoupper($method)){
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($error) throw new Exception('请求发生错误：' . $error);
        return  $data;
    }
   
    /**
    * PHP POST发送Json对象数据
    * @param $url 请求url
    * @param $jsonStr 发送的json字符串
    */
    function http_post_json($url, $jsonStr){
        
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST');
        header('Access-Control-Allow-Credentials: true'); 
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Content-Length: ' . strlen($jsonStr)
        )
        );
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    function addgoods($data,$goods_type_id,$color,$guige){
        $dfata['uid']=UID;
        $dfata['zymm_goods_id']=$data['zymm_goods_id'];
        $dfata['cate_id']=$goods_type_id;
        $dfata['goods_name']=$data['goods_name'];
        $dfata['goods_sn']=$data['goods_code'];
        $dfata['goods_attr']='NA';
        $dfata['chenfen']='NA';
        $dfata['unit']='件';
        $dfata['goods_color']=$color;
        $dfata['guige_mame']=$guige;
        $dfata['goods_price']=$data['market_sell_price'];
        $dfata['suppler_name']='自由买卖供应链';
        $dfata['suppler_price']=$data['vip_price'];
        $dfata['store_name']='';
        $dfata['store_kuwei']='';
        $dfata['warning_number']=$data['stock_warning'];
        $dfata['goods_img']=$data['goods_images'];
        $dfata['goods_video']=$data['goods_video'];
 
        $dfata['add_time']=time();
        $goods_id=M("user_goods")->add($dfata);    
        return $goods_id;
    }
    function add_goods_guige($yanse_chima,$info){
            $datr=[];
            $uid=UID;
            $model=M("user_goods_attr");
            $model->startTrans();
                foreach($yanse_chima as $k=>$val){
                    $datr['uid']=UID;
                    $datr['goods_id']=$info['add_goods_id'];
                    $datr['color']=$val['yanse'];
                    $datr['goods_name']=$info['goods_name'];
                    $datr['unit']='件';
                    $datr['chenfen']='';
                    $datr['guige_name']=$val['chima'];
                    $datr['price']=$val['product_price']+$info['goods_price'];
                    $datr['dis_price']=$val['product_price']+$info['goods_price2'];
                    $datr['add_time']=time();
                    $datr['goods_sn']=$val['product_sn'];
                    $datr['goods_attr']=$val['goods_code'];
                    $fgsrb[]=$datr;
                } 
             $model->addAll($fgsrb);
             $model->commit();
    }


        //分类检测
        function checkcate($cate_info){
            if($cate_info){
                $m2_id=0;
                $m1_id=0;
                $m3_id=$this->cheacdst($cate_info['cat_c'],0);
                if($cate_info['cat_b']['cat_name'] && $m3_id){
                    $m2_id=$this->cheacdst($cate_info['cat_b'],$m3_id);
                }
                if($cate_info['cat_a']['cat_name'] && $m2_id){
                    $m1_id=$this->cheacdst($cate_info['cat_a'],$m2_id);
                }else{
                    $m1_id=$this->cheacdst($cate_info['cat_a'],0);
                }
                if($m3_id){
                $cc=$m3_id;
            }
            if($m2_id){
                $cc=$m2_id;
            }
            if($m1_id){
                $cc=$m1_id;
            }
             return $cc;
            }
      }
        //检测分类是否存在
        function cheacdst($data,$pid){
            $where=[];
            $where['stype']=0;
            $where['uid']=UID;
            $where['pid']=$pid;
            $where['title']=$data['cat_name'];
            $model=M("user_mysql_cate");
            $id=$model->where($where)->getField('id');
            if(empty($id)){
                $goods_data['pid']=$pid;
                $goods_data['uid']=UID;
                $goods_data['stype']=0;
                $goods_data['add_time']=time();
                $goods_data['title']=$data['cat_name'];
                $adgid =$model->add($goods_data);
                return $adgid;
            }else{
                return $id;
            }
            
      }


}
